package com;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@SuppressWarnings("serial")
@WebServlet("/RulesServlet")
public class RulesServlet extends HttpServlet{
	private RulesManager rulesManager = new RulesManager();
	
	protected void doPost(HttpServletRequest request, HttpServletResponse response){
		if (request.getParameter("button") != null){
			// Handle editing a rule
			if (request.getParameter("button").equals("edit")){
				// Get the specific rule that is to be edited
				int ruleID = Integer.parseInt(request.getParameter("id"));
				Rule rule = rulesManager.queryRules(ruleID).get(0);
				request.setAttribute("rule", rule);
				
				// Now delete this rule
				rulesManager.deleteRule(request);
				try {
					// Redirect the user to the Define Rule page
					request.getRequestDispatcher("definerule.jsp").forward(request, response);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			// Handle deleting a rule
			else{
				rulesManager.deleteRule(request);
				
				try {
					// Redirect the user to the Rules page
					response.sendRedirect("rules.jsp");
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
	}
}